package com.chencq.core.utils.encrypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;

import com.chencq.core.utils.StringUtils;

/**
 * MD5加密码.
 * 
 * <p>
 * 
 * 调用java.security.MessageDigest中的MD5算法，获得数据摘要.
 *
 *
 */

public class MD5 {
  public MD5() {
  }
  /**
   * 计算MD5值.
   *
   * @param sourceData String
   * @return String MD5计算结果
   * @since BASE 0.1
   */
  public String getMD5Digest(String sourceData) {
     return  getMD5Digest(sourceData.getBytes());
  }

  /**
   * 直接对byte数组进行加密
   * @param sourceData 需要加密的byte数组
   * @return String 返回MD5计算结果字符串
   */
  public String getMD5Digest(byte[] sourceData) {
	    try {
	      MessageDigest alga = MessageDigest.getInstance("MD5");
	      alga.update(sourceData);
	      byte[] digesta = alga.digest();
	      return StringUtils.byteToHexString(digesta);
	    }
	    catch (NoSuchAlgorithmException ex) {
	      ex.printStackTrace();
	    }
	    return null;
	  } 
  
  public static void main(String[] args) throws IOException{
    MD5 m = new MD5();
//    String s = m.getMD5Digest("中国");
//    System.out.println(s);
    
    System.out.println(new Timestamp(System.currentTimeMillis()));
//    File a = new File("F:\\EBOOK\\Manning.jQuery.in.Action.Feb.2008.pdf");
    File a = new File("F:\\IBAK\\java\\eclipse-SDK-3.3.2-win32.zip");
    
    InputStream is = new FileInputStream(a);
    byte[] b = new byte[is.available()];
    System.out.println(new Timestamp(System.currentTimeMillis()));

    is.read(b);
    System.out.println(m.getMD5Digest(b));
    System.out.println(new Timestamp(System.currentTimeMillis()));
    
  }

}
